<?php

/*
 * Селектиране на избраното от менюто
 */
function tickMenu($path, $searchUrl)
{
	$break = explode('/', $searchUrl);

	if(strstr($break[3], $path))
		return true;
	else
		return false;
}

/*
 * Показване на избраното меню
 */
function selectedMenuTabs($path, $searchUrl)
{
	$break = explode('/', $searchUrl);

	if(strstr($break[2], $path))
		return true;
	else
		return false;
}

/*
 * Редирект според ролята
 */
function is_permission($role_id){
	if($role_id!=1)
		header('Location: access_denied.php');
}


/* Random Code */
function randomCode($length, $characters='123456789'){
 
    if ($characters == ''){ return ''; }
    $chars_length = strlen($characters)-1;
 
    mt_srand((double)microtime()*1000000);
 
    $pwd = '';
    while(strlen($pwd) < $length){
        $rand_char = mt_rand(0, $chars_length);
        $pwd .= $characters[$rand_char];
    }
 
    return $pwd;
}

/*
	print_r(get_files_by_ext('data/', 'txt'));
*/
function get_files_by_ext($path, $ext){
 
    $files = array();
 
    if (is_dir($path)){
        $handle = opendir($path); 
        while ($file = readdir($handle)) { 
            if ($file[0] == '.'){ continue; }
            if (is_file($path.$file) and preg_match('/\.'.$ext.'$/', $file)){ 
                $files[] = $file;
            } 
        }
        closedir($handle);
        sort($files);
    }
 
    return $files;
 
}


function checkURLlink($url){

	if(empty($url))
		return $url;
	else{
		$arrLinkParse = parse_url($url);

		if(empty($arrLinkParse['scheme']))
			$link = "http://".$arrLinkParse['path'];
		else
			$link = $url;

		return $link;
	}
}

function showInputLink($url){

	if(empty($url))
		return $url;
	else{
		$arrLinkParse = parse_url($url);

		if(empty($arrLinkParse['scheme']))
			$link = $arrLinkParse['path'];
		else
			$link = $arrLinkParse['host'];

		return $link;
	}
}


// Show extension filename
function get_fileExtension($file_name) {
	return end(explode(".", $file_name));
}

// Extension upload files
function getFileExtension($fileType, $fileName) {

	if($fileType=="application/vnd.ms-powerpoint")
		$extFile = get_fileExtension($fileName);
	else{
		$ext = explode("/", $fileType);
		$extFile = $ext[1];
	}

	return $extFile;
}

// Extension upload files
function getFileExtensionSound($fileType)
{
	switch ($fileType) {
		case 'audio/x-wav':
			return 'wav';
		break;
		case 'audio/mpeg':
			return 'mp3';
		break;
		case 'video/ogg':
			return 'ogg';
		break;
		default :
			return false;
		break;
	}
}

// Size upload files
function format_bytes($size) {
	$units = array(' B', ' KB', ' MB', ' GB', ' TB');
	for ($i = 0; $size >= 1024 && $i < 4; $i++) $size /= 1024;
		return round($size).$units[$i];
}

// Allow filetype
function allowExtension($ext){
	switch ($ext) {
		case 'image/gif':
			return true;
		break;
		case 'image/png':
			return true;
		break;
		case 'image/jpg':
			return true;
		case 'image/jpeg':
			return true;
		break;
		case 'application/pdf':
			return false;
		break;
		default :
			return false;
		break;
	}
}

// Allow filetype
function allowExtensionPDF($ext){
	switch ($ext) {
		case 'application/pdf':
			return true;
		break;
		case 'application/vnd.ms-powerpoint':
			return true;
		break;
		default :
			return false;
		break;
	}
}

// Allow filetype
function allowExtensionSounds($ext){
	switch ($ext) {
		case 'audio/x-wav':
			return true;
		break;
		case 'audio/mpeg':
			return true;
		break;
		case 'video/ogg':
			return true;
		break;
		default :
			return false;
		break;
	}
}


/**
*Function to truncate a string crop_str()
*/
function crop_str($string, $maxchar)
{
	//$charset = mb_internal_encoding("UTF-8");
	$charset = 'UTF-8';
	if(mb_strlen($string, $charset) > $maxchar)
		return mb_substr($string, 0, $maxchar, $charset).'...';
	else
		return mb_substr($string, 0, $maxchar, $charset);
}


/**
*Function to check length
*/
function strLength($string, $maxchar)
{
	$charset = 'UTF-8';
	if(mb_strlen($string, $charset) > $maxchar)
		return false;
	else
		return true;
}





/*
 * * formatSizeUnits($bytes)
 */
function formatSizeUnits($bytes)
{
	/*
        if ($bytes >= 1073741824){
            $bytes = 0;
        }
        if ($bytes >= 1073741824){
            $bytes = number_format($bytes / 1073741824, 2) . ' GB';
        }
        */

//        elseif($bytes >= 5242880){
//        elseif($bytes >= 1048576){
        if($bytes >= 4194304){
//	elseif($bytes >= 2097152){
		$bytes = 0;
        }
        /*
        elseif ($bytes >= 1048576){
            $bytes = number_format($bytes / 1048576, 2) . ' MB';
        }
        */
        elseif ($bytes >= 1024){
            //$bytes = number_format($bytes / 1024, 2) . ' KB';
            $bytes = 1;
        }
        elseif ($bytes > 1){
            //$bytes = $bytes . ' bytes';
            $bytes = 1;
        }
        elseif ($bytes == 1){
            //$bytes = $bytes . ' byte';
            $bytes = 1;
        }
        else{
            //$bytes = '0 bytes';
            $bytes = 0;
        }

        return $bytes;
}


function resizeToFile ($sourcefile, $newWidth=false, $newHeight=false, $targetfile, $jpegqual = 75, $extension)
{
	//setMemoryForImage($sourcefile);
	list($oldWidth, $oldHeight, $type) = getimagesize("$sourcefile");

	switch ($extension) {
		case 'gif' :
				$source_id = imagecreatefromgif($sourcefile);
			break;
		case 'png' :
				$source_id = imagecreatefrompng($sourcefile);
			break;
		case 'jpg' :
				$source_id =  imagecreatefromjpeg($sourcefile);
         break;
		case 'jpeg' :
				$source_id =  imagecreatefromjpeg($sourcefile);
			break;
	}


	# Maintains the aspect ration of the image and makes sure that it fits
	# within the maxW(newWidth) and maxH(newHeight) (thus some side will be smaller)
	$widthScale	= 2;
	$heightScale	= 2;

	// Check to see that we are not over resizing, otherwise, set the new scale
	if($newWidth) {
		if($newWidth > $oldWidth)
			$newWidth = $oldWidth;

		$widthScale = 	$newWidth / $oldWidth;
	}
	if($newHeight) {
		if($newHeight > $oldHeight)
			$newHeight = $oldHeight;

		$heightScale = $newHeight / $oldHeight;
	}

	//debug("W: $widthScale  H: $heightScale<br>");
	if($widthScale < $heightScale) {
		$maxWidth = $newWidth;
		$maxHeight = false;
	} elseif ($widthScale > $heightScale ) {
		$maxHeight = $newHeight;
		$maxWidth = false;
	} else {
		$maxHeight = $newHeight;
		$maxWidth = $newWidth;
	}

	if($maxWidth > $maxHeight){
		$applyWidth = $maxWidth;
		$applyHeight = ($oldHeight*$applyWidth)/$oldWidth;
	} elseif ($maxHeight > $maxWidth) {
		$applyHeight = $maxHeight;
		$applyWidth = ($applyHeight*$oldWidth)/$oldHeight;
	} else {
		$applyWidth = $maxWidth;
			$applyHeight = $maxHeight;
	}
	$startX = 0;
	$startY = 0;

	//create new image
	$target_id	= imagecreatetruecolor($applyWidth, $applyHeight);

	//put old image on top of new image
	$target_pic	= imagecopyresampled($target_id,$source_id, 0,0 , $startX, $startY, $applyWidth, $applyHeight, $oldWidth, $oldHeight);

	switch ($extension) {
		case 'gif' :
				imagegif($target_id, $targetfile, $jpegqual);
			break;
		case 'png' :
				imagealphablending($target_id, false);
				imagesavealpha($target_id, true);
				imagealphablending($source_id, true);
				imagecopyresampled($target_id,$source_id, 0,0 , $startX, $startY, $applyWidth, $applyHeight, $oldWidth, $oldHeight);
				imagepng($target_id, $targetfile);
			break;
		case 'jpg' :
				imagejpeg($target_id, $targetfile, $jpegqual);
			break;
		case 'jpeg' :
				imagejpeg($target_id, $targetfile, $jpegqual);
			break;
		default:
				return false;
			break;
	}

	@imagedestroy($target_id);
	@imagedestroy($source_id);
}


/* ПРОВЕРКА НА БРАУЗЕРА*/
function getBrowser()
{
	$u_agent = $_SERVER['HTTP_USER_AGENT'];
        $ub = '';
        if(preg_match('/MSIE/i',$u_agent))
        {
            $ub = "IЕ";
        }
        elseif(preg_match('/Firefox/i',$u_agent))
        {
            $ub = "MFirefox";
        }
        elseif(preg_match('/Safari/i',$u_agent))
        {
            $ub = "Safari";
        }
        elseif(preg_match('/Chrome/i',$u_agent))
        {
            $ub = "Chrome";
        }
        elseif(preg_match('/Flock/i',$u_agent))
         {
            $ub = "Flock";
        }
        elseif(preg_match('/Opera/i',$u_agent))
        {
            $ub = "Opera";
        }
        elseif(preg_match('/Netscape/i',$u_agent))
        {
            $ub = "Netscape";
        }

        return $ub;
    }

// Проверка на имейл адрес
function isValidEmail($email){
	return eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email);
}

// Показване на текущият месец
function currentMonth(){
	$curr_month = date("m");

	$month = array (1=> RIGHTBOX_JANUARY, RIGHTBOX_FEBRUARY, RIGHTBOX_MARCH, RIGHTBOX_APRIL, RIGHTBOX_MAY, RIGHTBOX_JUNE,
			RIGHTBOX_JULY, RIGHTBOX_AUGUST, RIGHTBOX_SEPTEMBER, RIGHTBOX_OCTOBER, RIGHTBOX_NOVEMBER, RIGHTBOX_DECEMBER);

	foreach ($month as $key => $val)
	{
		if ($key == $curr_month)
			return $val;
	}
}

function cropStr($string, $maxchar)
{
	//$charset = mb_internal_encoding("UTF-8");
	$charset = 'UTF-8';
	if(mb_strlen($string, $charset) > $maxchar)
		return mb_substr($string, 0, $maxchar, $charset).'...';
	else
		return mb_substr($string, 0, $maxchar, $charset);
}

// SELF URL address
function selfURL() {
	$s = empty($_SERVER["HTTPS"]) ? ''
		: ($_SERVER["HTTPS"] == "on") ? "s"
		: "";
	$protocol = strleft(strtolower($_SERVER["SERVER_PROTOCOL"]), "/").$s;
	$port = ($_SERVER["SERVER_PORT"] == "80") ? ""
		: (":".$_SERVER["SERVER_PORT"]);
	return $protocol."://".$_SERVER['SERVER_NAME'].$port.$_SERVER['REQUEST_URI'];
}
function strleft($s1, $s2) {
	return substr($s1, 0, strpos($s1, $s2));
}

// Check is http OR https
function getCurrentURL() {
	$s = empty($_SERVER["HTTPS"]) ? '': ($_SERVER["HTTPS"] == "on") ? "s" : "";
	$protocol = strleft(strtolower($_SERVER["SERVER_PROTOCOL"]), "/").$s;
	$port = ($_SERVER["SERVER_PORT"] == "80") ? "" : (":".$_SERVER["SERVER_PORT"]);
	return $protocol."://".$_SERVER['SERVER_NAME'].$port.$_SERVER['REQUEST_URI'];
}

function escape_data_filter($string) {
	//$escape	= trim(strip_tags($string));
	$escape	= trim($string);
	$data	= mysql_real_escape_string($escape);

    return $data;
}
?>